<template>
  <div id="house">
    <van-overlay :show="showLoading">
      <van-loading color="#fff" size="100px" type="spinner" />
    </van-overlay>
    <div class="bottom-page" ref="bottom">
      <div class="head-line">
        <img
          src="@/assets/icon/arrow-l.png"
          @click="$router.push('/about')"
          alt
        />
        <h2>房屋详情</h2>
        <span></span>
      </div>
      <div class="houseInfor">
        <!-- <h2>房屋基本信息</h2> -->
        <p>户主：{{ house.name }}</p>
        <p>身份证号: {{ house.idcard }}</p>
        <p>门牌号: {{ house.doorno }}</p>
        <p>房型: {{ house.housetype }}</p>
        <p>结构类型: {{ house.structure }}</p>
        <p>验收标准: {{ house.projectstatus }}</p>
        <p>所在村组：{{ house.village }} {{ house.address }}</p>
      </div>
      <div class="inspect-list">
        <div class="inspect-head">
          <h4>房屋巡查记录</h4>
          <div class="add" @click="showD()">+ 新增</div>
        </div>
        <div class="table">
          <div class="table-item" v-for="item in inspectList" :key="item.id">
            <img :src="getBase(item.picture)" alt="" />
            <div class="item-content">
              <div class="time">巡查时间：{{ formatDate(item.checkdate) }}</div>
              <p class="describe">描述：{{ item.localedescribe }}</p>
              <div class="isrectify">是否需要整改：{{ item.isrectify }}</div>
              <div class="step">整改步骤：{{ item.rectifystep }}</div>
              <!-- <div class="more" @click="showD(item)">查看详情</div> -->
            </div>
            <div class="item-demo" @click="showD(item)"></div>
          </div>
        </div>
      </div>
    </div>
    <!-- 巡查详情弹出层 -->
    <!-- <div class="demo-out" v-if="showDemo"> -->
      <van-overlay :show="showDemo" :lock-scroll="false">
      <!-- <img src="@/assets/icon/close.svg" alt="" @click="showDemo = false" /> -->
      <div class="demo-in">
        <div class="demo-inner">
          <div><span>户主：</span> {{ house.name }}</div>
          <div><span>门牌号：</span> {{ house.doorno }}</div>
          <div><span>工程状态：</span> {{ house.projectstatus }}</div>
          <div>
            <span>所在村组：</span> {{ house.village }} {{ house.address }}
          </div>
          <div>
            <span> 巡查人： </span>
            <input type="text" v-model="demoObj.checker" />
          </div>
          <div>
            <span>巡查时间： </span>
            <div
              class="time"
              v-html="demoObj.checkdate"
              @click="showPicker = true"
            ></div>
          </div>
          <div>
            <span>现场照片：</span>
            <van-uploader
              v-model="XCfileList"
              :after-read="XCRead"
              :max-count="1"
            />
          </div>
          <div class="textarea">
            <span>现场情况：</span>
            <textarea
              name=""
              id=""
              cols="30"
              rows="4"
              v-model="demoObj.localedescribe"
            ></textarea>
          </div>
          <div class="switch">
            <span>是否停工：</span>
            <van-switch v-model="demoObj.pause" :size="switchSize + 'px'" />
            {{ demoObj.pause ? "是" : "否" }}
          </div>
          <div class="switch">
            <span>是否需要整改：</span>
            <van-switch v-model="demoObj.isrectify" :size="switchSize + 'px'" />
            {{ demoObj.isrectify ? "是" : "否" }}
          </div>
          <div class="rectifyDemo" v-if="demoObj.isrectify">
            <div class="switch">
              <span>整改是否完成：</span>
              <van-switch
                v-model="demoObj.iscompelte"
                :size="switchSize + 'px'"
              />
              {{ demoObj.iscompelte ? "是" : "否" }}
            </div>
            <div>
              <span>整改证明：</span>
              <van-uploader
                v-model="ZMfileList"
                :after-read="ZMRead"
                :max-count="1"
              />
            </div>
            <div>
              <span>整改完成现场照片：</span>
              <van-uploader
                v-model="WCfileList"
                :after-read="WCRead"
                :max-count="1"
              />
            </div>
            <div class="textarea">
              <span>整改措施：</span>
              <textarea
                name=""
                id=""
                cols="30"
                rows="4"
                v-model="demoObj.rectifystep"
              ></textarea>
            </div>
          </div>
        </div>
        <div class="btns">
          <button @click="cancelSubmit">取消</button>
          <button @click="submit">确定</button>
        </div>
      </div>
      <van-popup v-model="showPicker" position="bottom">
        <van-datetime-picker
          v-model="pickTime"
          :item-height="optionHeight"
          type="date"
          show-toolbar
          :min-date="minDate"
          :max-date="maxDate"
          @cancel="onCancel"
          @confirm="onConfirm"
        />
      </van-popup>
    <!-- </div> -->
    </van-overlay>
  </div>
</template>

<script>
import api from "@/api/api.js";
import axios from "axios";
import local from "@/util/localstorage.js";
import noimg from "@/assets/img/noimg.png";

export default {
  name: "house",
  data() {
    return {
      showLoading: true,
      house: {},
      inspectList: [],
      titleList: ["工程状态", "巡查时间", "现场情况", "是否整改", "操作"],
      showDemo: false,
      showPicker: false,
      demoObj: {
        pause: false,
        isrectify: false,
        iscompelte: false,
        checkdate: "",
      },
      switchSize: 50,
      optionHeight: 60,
      minDate: new Date("1990-01-01"),
      maxDate: new Date("2030-01-01"),
      // 选择器内的时间   如果直接绑定obj内的时间则造成滑动的时候就直接改变
      pickTime: new Date(),
      XCfileList: [],
      // XCfileIdlist: [],
      ZMfileList: [],
      // ZMfileIdlist: [],
      WCfileList: [],
      // WCfileIdlist: [],
      imgHead:
        "http://house.ksljz.cn:8081/house/platform/system/sysFile/getFileById.do?fileId=",
    };
  },
  // computed: {
  //   checkdate() {
  //     return this.formatDate();
  //   },
  // },
  methods: {
    // 获取房屋数据
    getMore() {
      let id = this.$route.params.id;
      api
        .getHouseMore({ id })
        .then((res) => {
          console.log(res.data.jsonData.housePatrolList);
          this.showLoading = false;
          this.house = res.data.jsonData.houseBase;
          local.setLoaclStorage('houseInfo', this.house)
          this.inspectList = res.data.jsonData.housePatrolList;
        })
        .catch((error) => {
          // console.log(error)
          this.showLoading = false;
          this.$toast.fail("连接超时");
        });
    },
    getBase(item) {
      // console.log(item)
      if (!item) {
        return noimg;
      }
      var obj = JSON.parse(item).attachs[0];
      if(!obj){
        return noimg
      }
      return obj.fileSrc;
    },
    // 格式化时间戳     自定义返回  年月日时分秒
    formatDate(date) {
      var now = new Date(date);
      var year = now.getFullYear();
      // var year = now.getYear();     //  为啥是120
      // console.log(year);
      var month = now.getMonth() + 1;
      // if (month < 10) {
      //   month = "0" + month;
      // }
      month = (month + "").padStart(2, "0");
      var date = now.getDate();
      // if (date < 10) {
      //   date = "0" + date;
      // }
      date = (date + "").padStart(2, "0");
      var hour = now.getHours();
      var minute = now.getMinutes();
      var second = now.getSeconds();
      return year + "-" + month + "-" + date;
    },
    // 新增或者查看按钮
    showD(obj) {
      console.log(obj);
      if(obj){
        local.setLoaclStorage('rectifyOrder',obj);
      }else {
        local.setLoaclStorage('rectifyOrder','');
      }
      this.$router.push('/rectify')
      return

      this.showDemo = true;
      // 因为picktime在在滑动的时候已经被更改了   那么直接每次创建这个时间就行
      this.demoObj.checkdate = this.formatDate(new Date());
      this.demoObj.checker = local.getLoaclStorage("userInfo").fullname;
      this.$nextTick(() => {
        // document.querySelector(".demo-out").ontouchmove = function (e) {
        //   // console.log(e.target);
        //   if (e.target.tagName !== 'TEXTAREA') {
        //     e.stopPropagation();
        //     e.preventDefault();
        //   }
        // };
      });
      if (obj) {
        Object.assign(this.demoObj, obj);
        this.demoObj.pause = this.demoObj.pause == "是" ? true : false;
        this.demoObj.isrectify = this.demoObj.isrectify == "是" ? true : false;
        this.demoObj.iscompelte =
          this.demoObj.iscompelte == "是" ? true : false;
        this.demoObj.checkdate = this.formatDate(this.demoObj.checkdate);
        this.pickTime = new Date(obj.checkdate); // 把时间选择器也绑定上时间
        if (obj.picture) {
          // console.log(this.imgHead + JSON.parse(obj.picture).attachs[0].fileId)
          let item1 = {
            url: this.imgHead + JSON.parse(obj.picture).attachs[0].fileId,
            isImage: true,
          };
          this.XCfileList[0] = item1;
        }
        if (obj.zgzmfile) {
          let item2 = {
            url: this.imgHead + JSON.parse(obj.zgzmfile).attachs[0].fileId,
            isImage: true,
          };
          this.ZMfileList[0] = item2;
        }
        if (obj.zgwcxczpfile) {
          let item3 = {
            url: this.imgHead + JSON.parse(obj.zgwcxczpfile).attachs[0].fileId,
            isImage: true,
          };
          this.WCfileList[0] = item3;
        }
      }
    },
    // 时间选择器的取消
    onCancel() {
      this.pickTime = new Date(this.demoObj.checkdate);
      this.showPicker = false;
      // this.demoObj.isrectify = false;
    },
    // 时间选择器的确定
    onConfirm(value) {
      // console.log('点击到确定按钮了', value);
      this.pickTime = value;
      this.demoObj.checkdate = this.formatDate(value);
      this.showPicker = false;
    },
    async XCRead(file) {
      // 此时可以自行将文件上传至服务器
      // console.log(file.content);

      let afterCompressBase64 = await this.compressImg(file.content, 0.1);
      var formdata1 = new FormData(); // 创建form对象
      formdata1.append("img", file.file, file.file.name); // 通过append向form对象添加数据,可以通过append继续添加数据
      let config = {
        headers: { "Content-Type": "multipart/form-data" },
      }; //添加请求头
      axios
        .post(
          "http://house.ksljz.cn:8081/house/platform/system/sysFile/fileUpload.do",
          formdata1,
          config
        )
        .then((response) => {
          //这里的/xapi/upimage为接口
          console.log(response.data);
          this.demoObj.picture = {
            attachs: [
              { fileId: response.data.fileId, fileSrc: afterCompressBase64 },
            ],
          };
          this.demoObj.picture = JSON.stringify(this.demoObj.picture);
        });
    },
    async ZMRead(file) {
      // 此时可以自行将文件上传至服务器
      // console.log(file.content);

      let afterCompressBase64 = await this.compressImg(file.content, 0.1);
      console.log(afterCompressBase64);
      var formdata1 = new FormData(); // 创建form对象
      formdata1.append("img", file.file, file.file.name); // 通过append向form对象添加数据,可以通过append继续添加数据
      let config = {
        headers: { "Content-Type": "multipart/form-data" },
      }; //添加请求头
      axios
        .post(
          "http://house.ksljz.cn:8081/house/platform/system/sysFile/fileUpload.do",
          formdata1,
          config
        )
        .then((response) => {
          //这里的/xapi/upimage为接口
          console.log(response.data);
          this.demoObj.zgzmfile = {
            attachs: [
              { fileId: response.data.fileId, fileSrc: afterCompressBase64 },
            ],
          };
          this.demoObj.zgzmfile = JSON.stringify(this.demoObj.zgzmfile);
        });
    },
    async WCRead(file) {
      // 此时可以自行将文件上传至服务器
      // console.log(file.content);

      let afterCompressBase64 = await this.compressImg(file.content, 0.1);
      var formdata1 = new FormData(); // 创建form对象
      formdata1.append("img", file.file, file.file.name); // 通过append向form对象添加数据,可以通过append继续添加数据
      let config = {
        headers: { "Content-Type": "multipart/form-data" },
      }; //添加请求头
      axios
        .post(
          "http://house.ksljz.cn:8081/house/platform/system/sysFile/fileUpload.do",
          formdata1,
          config
        )
        .then((response) => {
          //这里的/xapi/upimage为接口
          console.log(response.data);
          this.demoObj.zgwcxczpfile = {
            attachs: [
              { fileId: response.data.fileId, fileSrc: afterCompressBase64 },
            ],
          };
          this.demoObj.zgwcxczpfile = JSON.stringify(this.demoObj.zgwcxczpfile);
        });
    },
    cancelSubmit() {
      this.showDemo = false;
      this.demoObj = this.$options.data().demoObj;
      this.XCfileList = [];
      this.ZMfileList = [];
      this.WCfileList = [];
    },
    submit() {
      // 校验表单内必填事项是有空值
      var arr = ["picture", "localedescribe"];
      var re = arr.every((item) => Boolean(this.demoObj[item]));
      // console.log(re)
      if (!re) {
        this.$toast.fail({ message: "数据未填写完整", forbidClick: true });
        return;
      }

      this.$toast.loading({ message: "加载中...", forbidClick: true });
      var obj = {
        id: this.demoObj.id,
        houseid: this.$route.params.id,
        name: this.house.name,
        doorno: this.house.doorno,
        address: this.house.address,
        village: this.house.village,
        town: this.house.town,
        xy: this.house.xy,
        projectstatus: this.house.projectstatus,
        checker: this.demoObj.checker,
        checkdate: this.demoObj.checkdate,
        localedescribe: this.demoObj.localedescribe,
        picture: this.demoObj.picture, // 现场照片
        pause: this.demoObj.pause ? "是" : "否",
        isrectify: this.demoObj.isrectify ? "是" : "否",
        rectifystep: this.demoObj.rectifystep,
        iscompelte: this.demoObj.iscompelte ? "是" : "否",
        attach: "",
        remark: "",
        zgzmfile: this.demoObj.zgzmfile, // 整改证明图片
        zgwcxczpfile: this.demoObj.zgwcxczpfile, // 整改完成照片
        createBy: this.demoObj.checker,
        // createtime: new Date(),    // 防止创建时间一直被更改
        updatetime: null,
        updateBy: null,
        runId: null,
      };
      // 如果有id则说明是编辑  那么保存新增更新时间和更新人即可
      if (this.demoObj.id) {
        // obj.createBy = this.demoObj.createBy;
        obj.createtime = this.formatDate(this.demoObj.createtime);
        obj.updatetime = this.formatDate(new Date());
        obj.updateBy = this.demoObj.checker;
      } else {
        obj.createtime = this.formatDate(new Date());
      }
      var jsonData = JSON.stringify(obj);
      api
        .saveInspect(obj)
        .then((res) => {
          console.log(res);
          // this.showLoading = false;
          this.$toast.clear();
          if (res.data.success) {
            this.$toast.success("成功");
          } else {
            this.$toast.fail("失败");
          }
          // 不论成功与否  都得清除表单  重新拉出一下房屋巡查记录
          this.cancelSubmit();
          setTimeout(() => {
            this.getMore();
            // window.location.reload()
          }, 1500);
        })
        .catch((error) => {
          // console.log(error)
          this.$toast.clear();
          this.$toast.fail("连接超时");
        });
    },

    compressImg(base64String, quality) {
      // 获取图片类型  image/png  image/jpg 之类的
      var getMimeType = function (urlData) {
        var arr = urlData.split(",");
        var mime = arr[0].match(/:(.*?);/)[1];
        return mime;
      };
      var newImage = new Image();
      var originWidth, originHeight;

      var promise = new Promise((resolve) => (newImage.onload = resolve));
      newImage.src = base64String;
      return promise.then(() => {
        originWidth = newImage.width;
        originHeight = newImage.height;
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        // 最大尺寸限制
        var maxWidth = 80,
          maxHeight = 80;
        // 目标尺寸
        var targetWidth = originWidth,
          targetHeight = originHeight;
        if (originWidth > maxWidth || originHeight > maxHeight) {
          if (originWidth / originHeight > maxWidth / maxHeight) {
            // 更宽，按照宽度限定尺寸
            targetWidth = maxWidth;
            targetHeight = Math.round(maxWidth * (originHeight / originWidth));
          } else {
            targetHeight = maxHeight;
            targetWidth = Math.round(maxHeight * (originWidth / originHeight));
          }
        }

        // canvas对图片进行缩放
        canvas.width = targetWidth;
        canvas.height = targetHeight;
        // console.log(newImage)
        ctx.clearRect(0, 0, targetWidth, targetHeight);
        ctx.drawImage(newImage, 0, 0, targetWidth, targetHeight);
        // document.body.appendChild(canvas)
        var base64 = canvas.toDataURL(getMimeType(base64String), quality);
        return base64;
      });
    },

    getimg() {
      var file = this.$refs.img.files[0];
      console.log(file);
      var formdata1 = new FormData(); // 创建form对象
      formdata1.append("img", file, file.name); // 通过append向form对象添加数据,可以通过append继续添加数据
      //或formdata1.append('img',file);
      let config = {
        headers: { "Content-Type": "multipart/form-data" },
      }; //添加请求头
      console.log(formdata1);
      axios
        .post(
          "http://house.ksljz.cn:8081/house/platform/system/sysFile/fileUpload.do",
          formdata1,
          config
        )
        .then((response) => {
          //这里的/xapi/upimage为接口
          console.log(response.data);
        });
    },
  },
  created() {
    this.getMore();

    // 控制背景色
    var bg = document.querySelector("body");
    bg.style.backgroundColor = "#f2f2f2";

    this.optionHeight = (document.documentElement.clientHeight * 60) / 1334;
    this.switchSize = (document.documentElement.clientWidth * 50) / 750;
  },
};
</script>

<style lang='scss' scoped>
#house {
  width: 100%;
  position: relative;
  background-color: #f2f2f2;
  font-size: 14px;
  .van-loading {
    margin-top: 80%;
  }
  .bottom-page {
    background-color: #eeeeee;
    .head-line {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 42px;
      padding: 0 23px;
      color: white;
      font-family: PingFangSC-Regular, sans-serif;
      background-color: #2e9be9;
      box-sizing: border-box;
      h2 {
        padding: 0;
        font-size: 20px;
        font-family: Adobe Heiti Std;
        font-weight: normal;
        color: #ffffff;
      }
      img {
        width: 20px;
        height: 20px;
      }
      span {
        display: inline-block;
        height: 30px;
        width: 40px;
        line-height: 30px;
      }
    }
    .houseInfor {
      margin: 10px auto;
      width: 340px;
      // height: 213px;
      color: #ffffff;
      box-sizing: border-box;
      text-align: left;
      border-radius: 6px;
      background: url("~@/assets/img/house.png") no-repeat right bottom/120px
          104px,
        linear-gradient(0deg, #2e9be9 0%, #25c3f8 100%);
      overflow: hidden;
      h2 {
        margin: 5px 0 5px 10px;
        font-family: Adobe Heiti Std;
        font-weight: normal;
      }
      p {
        // display: inline-table;
        // width: 50%;
        font-size: 16px;
        margin-left: 10px;
        line-height: 30px;
        &:last-child {
          width: 100%;
        }
      }
    }
    .inspect-list {
      width: 100%;
      box-sizing: border-box;
      .inspect-head {
        position: relative;
        padding: 0 17px;
        text-align: left;
        color: #0577c8;
        h4 {
          display: inline-block;
          margin: 10px 0 10px 8px;
          font-family: Adobe Heiti Std;
          font-weight: bold;
        }
        .add {
          position: absolute;
          right: 17px;
          bottom: 6px;
          padding: 3px;
        }
      }
      .table {
        margin: 0 auto;
        width: calc(100% - 34px);
        .table-item {
          position: relative;
          width: 340px;
          height: 115px;
          margin-bottom: 10px;
          background-color: #f2f2f2;
          box-shadow: 0 0 5px rgb(194, 194, 194);
          img {
            margin: 5px 0 0 7px;
            width: 104px;
            height: 104px;
          }
          .item-content {
            display: inline-block;
            vertical-align: top;
            margin: 5px 0 5px 10px;
            padding-right: 10px;
            width: calc(100% - 131px);
            height: 100px;
            text-align: left;
            line-height: 22px;
            font-family: Adobe Heiti Std;
            .describe,
            .step {
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
            }
            // .more {
            //   text-align: right;
            //   color: #0577C8;
            // }
          }
          .item-demo {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }
  .van-overlay {
  // .demo-out {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    // z-index: 10;
    background-color: rgba(0, 0, 0, 0.8);
    // > img {
    //   position: absolute;
    //   right: 5%;
    //   top: 5%;
    //   border: 1px solid #fff;
    // }
    .demo-in {
      position: absolute;
      width: 90%;
      height: 70%;
      margin: 0 auto;
      top: 50%;
      left: 50%;
      padding: 10px;
      border-radius: 5px;
      box-sizing: border-box;
      background-color: #fff;
      transform: translate(-50%, -50%);
      overflow: hidden;
      .demo-inner {
        width: calc(100%);
        height: calc(100% - 40px);
        overflow-y: auto;
        > div {
          width: 100%;
          text-align: left;
          span {
            display: inline-block;
            vertical-align: top;
            line-height: 25px;
            width: 100px;
          }
          input {
            border: 1px solid rgb(170, 170, 170);
          }
          > .time {
            display: inline-block;
            line-height: 23px;
            width: 166px;
            border: 1px solid rgb(170, 170, 170);
          }
        }
        .textarea {
          margin-top: 10px;
          span {
            vertical-align: top;
          }
          textarea {
            width: calc(100% - 120px);
            border: 1px solid rgb(170, 170, 170);
          }
        }
        .switch {
          display: flex;
          align-items: center;
          line-height: 30px;
        }
        .rectifyDemo {
          .textarea {
            margin-top: 10px;
            span {
              vertical-align: top;
            }
            textarea {
              border: 1px solid rgb(170, 170, 170);
            }
          }
        }
      }
      .btns {
        position: absolute;
        bottom: 0px;
        left: 10px;
        width: 100%;
        height: 50px;
        margin-top: 10px;
        text-align: center;
        button {
          padding: 5px 10px;
          margin: 10px;
        }
      }
    }
  }
}
</style>
